package com.seio.edc.controller.system.customerinfo;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.Response;

import com.nova.edc.model.system.*;
import com.nova.edc.model.util.ExcelArea;
import com.nova.edc.service.system.*;
import com.seio.edc.controller.energy.EnergyController;
import com.seio.edc.util.ExcelReadUtil;
import com.seio.edc.util.ExcelUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.nova.frame.dao.pager.Page;
import com.nova.frame.dao.pager.PageList;
import com.nova.frame.utils.DateUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;

@Controller
@RequestMapping(value = "/system/customerinfo")
public class CustomerinfoController {

    static Logger log = Logger.getLogger(CustomerinfoController.class);

    /**
     * 客户信息
     */
    @Autowired
    private com.nova.edc.service.system.CustomerInfoService novaCustomerInfoService;

    @Autowired
    private GroupService novaGroupService;

    @Autowired
    private ElecPriceService novaElecPriceService;

    @Autowired
    private PointLightService pointLightService;

    @Autowired
    private ArchitectureService novaarchitectureService;

    @Autowired
    private RoleService novaroleService;

    private static final int PAGE_SIZE = 10;

    @InitBinder("custEntity")
    public void initBinder1(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("custEntity.");
    }

    /**
     * 客户列表
     */
    @RequestMapping(value = "customerList")
    public ModelAndView customerList(HttpServletRequest request, HttpServletResponse response,
                                     HttpSession session, ModelMap modelMap, Integer pageIndex,
                                     String customerName, String customertype, Integer companyCode) {
        Login login = (Login) session.getAttribute("sessionLogin");
        if (novaroleService.findByType(ModelConstant.ROLE_COMMON).get(0).getId() == login.getRoleid()) {
            CustomerArea customerArea = new CustomerArea();
            customerArea.setCustomerinfoid(login.getCustomerinfoid());
            return new ModelAndView(new RedirectView("/energy/AreaEnergy.shtml?customerinfoid=" + login.getCustomerinfoid()));
        } else {
            Page page = new Page();
            page.setCurrentPage(pageIndex == null || pageIndex == 0 ? 1 : pageIndex);
            page.setPageSize(PAGE_SIZE);
            PageList<CustomerInfo> customerInfoList = novaCustomerInfoService
                    .findCustomerInfoPageListByRole(login, companyCode,
                            customerName, null, page, "", "asc");
            modelMap.put("pageIndex", page.getCurrentPage());
            modelMap.put("dataCount", page.getRowCount());
            modelMap.put("pageCount", page.getTotalPage());
            modelMap.put("companyCode", companyCode);
            modelMap.put("customerName", customerName);
            modelMap.put("customerInfoList", customerInfoList.getDatas());
            return new ModelAndView("customerMap/customerList", modelMap);
        }
    }

    /**
     * 空调客户列表
     */
    @RequestMapping(value = "aircustomerList")
    public ModelAndView aircustomerList(HttpServletRequest request,
                                        HttpSession session, ModelMap modelMap, Integer pageIndex,
                                        String customerName) {

        Login login = (Login) session.getAttribute("sessionLogin");
        Page page = new Page();
        page.setCurrentPage(pageIndex == null || pageIndex == 0 ? 1 : pageIndex);
        page.setPageSize(PAGE_SIZE);
        PageList<CustomerInfo> customerInfoList = novaCustomerInfoService
                .findCustomerInfoPageListByRole(login, 0,
                        customerName, ModelConstant.CUSTOMERINFO_TYPE_POWER, page, "", "desc");
        modelMap.put("pageIndex", page.getCurrentPage());
        modelMap.put("dataCount", page.getRowCount());
        modelMap.put("pageCount", page.getTotalPage());
        modelMap.put("customerInfoList", customerInfoList.getDatas());
        return new ModelAndView("airdata/customerAirList", modelMap);
    }

    /**
     * 客户信息主页面
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "customerMain")
    public ModelAndView customerMain(HttpServletRequest request,
                                     HttpSession session, Integer pageIndex, ModelMap modelMap,
                                     @ModelAttribute("customerInfo") CustomerInfo customerInfo) {
        // 当前页数
        Page page = new Page();
        page.setCurrentPage(pageIndex == null || pageIndex == 0 ? 1 : pageIndex);
        page.setPageSize(PAGE_SIZE);
        modelMap.put("pageIndex", page.getCurrentPage());
        // 获取数据为当前登录用户添加的数据
        String loginName = (String) session.getAttribute("loginname");
        customerInfo.setAddby(loginName);
        PageList<CustomerInfo> pageList = novaCustomerInfoService
                .findCustomerInfoPageList(customerInfo, page, "AddDate", "desc");
        modelMap.put("dataCount", page.getRowCount());
        modelMap.put("pageCount", page.getTotalPage());
        modelMap.put("groupList", novaGroupService.findAllGroup());
        // 数据列表
        modelMap.put("custList", pageList.getDatas());
        // 获取表单值并封装到实体内
        return new ModelAndView("system/customerinfo/customerinfoMain",
                modelMap);
    }

    /**
     * 用户信息---新增初期设定
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "customerinfoNewInit")
    public ModelAndView customerinfoNewInit(HttpServletRequest request,
                                            HttpSession session, ModelMap modelMap, Integer id) {
        try {
            Login login = (Login) session.getAttribute("sessionLogin");
            if (id != null && id != 0) {
                CustomerInfo customerInfo = novaCustomerInfoService.getById(id);
                modelMap.put("customerInfo", customerInfo);
            }
            List<ElecPrice> lstuntice = novaElecPriceService
                    .findElecPriceByUser(login.getId());
            modelMap.put("groupList", novaGroupService.findAllGroup());
            modelMap.put("lstuntice", lstuntice);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Architecture> architectureList = novaarchitectureService.findAll();
        modelMap.put("architectureList", architectureList);
        return new ModelAndView("system/customerinfo/customerinfoNew", modelMap);
    }

    /**
     * 客户信息---修改
     *
     * @param request
     * @param modelMap
     * @return
     */

    @RequestMapping(value = "save")
    public ModelAndView save(HttpServletRequest request, HttpSession session,
                             ModelMap modelMap, CustomerInfo customerInfo) {
        Login login = (Login) session.getAttribute("sessionLogin");
        // 保存数据时根据groupcode获取name，添加客户的所属集团信息
        if (customerInfo.getGroupcode() != null && customerInfo.getGroupcode() != 0) {
            Group group = novaGroupService.getByGroupCode(customerInfo.getGroupcode());
            if (group != null) {
                customerInfo.setGroupname(group.getGroupname());
            }
        }
        if (customerInfo.getId() != null && customerInfo.getId() != 0) {
            customerInfo.setModifyby(login.getUsername());
            customerInfo.setModifydate(DateUtils.getCurrentDate());
            customerInfo.setModifystamp(DateUtils.getCurrentDate());
            novaCustomerInfoService.update(customerInfo);
        } else {
            customerInfo.setAddby(login.getUsername());
            customerInfo.setAdddate(DateUtils.getCurrentDate());
            novaCustomerInfoService.insert(customerInfo);
        }
        return customerMain(request, session, 1, modelMap, new CustomerInfo());
    }

    /**
     * 客户信息---删除
     *
     * @param request
     * @param modelMap
     * @return
     */

    @RequestMapping(value = "customerinfoDelete")
    public ModelAndView customerinfoDelete(HttpServletRequest request,
                                           HttpSession session, ModelMap modelMap, Integer id,
                                           CustomerInfo customerInfo) {
        try {
            if (id != null && id != 0) {
               /*
               //删设备
                PointAir pointAir = new PointAir();
                pointAir.setCustomerinfoid(id);
                pointAirService.delete(pointAir);
                PointLight pointLight = new PointLight();
                pointLight.setCustomerinfoid(id);
                pointLightService.delete(pointLight);
                CustomerArea customerArea = new CustomerArea();
                customerArea.setCustomerinfoid(id);
                //删节点
                List<CustomerArea> customerAreas = novaCustomerAreaService.findCustomerArea(customerArea);
                for (CustomerArea ele : customerAreas) {
                    AreaPoint areaPoint = new AreaPoint();
                    areaPoint.setAreaid(ele.getId());
                    novaAreaPointService.delete(areaPoint);
                }
                //删区域
                novaCustomerAreaService.deleteByCustomerArea(customerArea);
                */
                novaCustomerInfoService.deleteById(id);
            }
        } catch (Exception e) {
            String msg = "删除出错，请联系管理员！";
            modelMap.put("msg", msg);
        }
        return customerMain(request, session, 1, modelMap, customerInfo);

    }

    /**
     * 验证公司番号是否存在
     */
    @RequestMapping(value = "companyCodeVali.shtml")
    @ResponseBody
    public Map<String, Object> userNameVali(HttpServletRequest request,
                                            Integer companyCode, Integer customerinfoid) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("existFlag", novaCustomerInfoService.isExistCompanyCode(
                companyCode, customerinfoid));
        return map;
    }

    /**
     * 通过ajax修改客户信息
     */
    @RequestMapping(value = "ajaxUpdate.shtml")
    @ResponseBody
    public int ajaxUpdate(HttpServletRequest request, HttpSession session,
                          ModelMap modelMap, @RequestBody CustomerInfo customerInfo) {
        Login login = (Login) session.getAttribute("sessionLogin");
        customerInfo.setModifyby(login.getUsername());
        customerInfo.setModifydate(DateUtils.getCurrentDate());
        customerInfo.setModifystamp(DateUtils.getCurrentDate());
        return novaCustomerInfoService.update(customerInfo);
    }

    /**
     * 客户信息录入
     */
    @RequestMapping(value = "inputCustomerInfo.shtml")
    @ResponseBody
    public boolean inputCustomerInfo(@RequestParam(value = "file", required = false) MultipartFile file, HttpSession session) throws IOException {
        CustomerInfo customerInfo = new CustomerInfo();
        Login login = (Login) session.getAttribute("sessionLogin");
        try {
            List<CustomerInfo> customerInfoList = (List<CustomerInfo>) ExcelReadUtil.excelToData(0, 2, customerInfo, file);
            novaCustomerInfoService.insertByExcel(customerInfoList, login);
            log.info("客户数量" + customerInfoList.size());
            return true;
        } catch (Exception e) {//java.lang.NullPointerException
            e.printStackTrace();
            return false;
        }


    }

    /**
     * 设备信息导入
     */
    @RequestMapping(value = "inputDevice.shtml")
    @ResponseBody
    public boolean inputDevice(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        try {
            List<ExcelArea> pointLightList = ExcelUtil.excelToArea(file);
            pointLightService.insertByExcel(pointLightList);
            log.info("客户数量" + pointLightList.size());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


    }
}
